{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n# Legend guide\n\n\nGenerating legends flexibly in Matplotlib.\n\n.. currentmodule:: matplotlib.pyplot\n\nThis legend guide is an extension of the documentation available at\n:func:`~matplotlib.pyplot.legend` - please ensure you are familiar with\ncontents of that documentation before proceeding with this guide.\n\n\nThis guide makes use of some common terms, which are documented here for clarity:\n\n.. glossary::\n\n    legend entry\n        A legend is made up of one or more legend entries. An entry is made up of\n        exactly one key and one label.\n\n    legend key\n        The colored/patterned marker to the left of each legend label.\n\n    legend label\n        The text which describes the handle represented by the key.\n\n    legend handle\n        The original object which is used to generate an appropriate entry in\n        the legend.\n\n\nControlling the legend entries\n==============================\n\nCalling :func:`legend` with no arguments automatically fetches the legend\nhandles and their associated labels. This functionality is equivalent to::\n\n    handles, labels = ax.get_legend_handles_labels()\n    ax.legend(handles, labels)\n\nThe :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns\na list of handles/artists which exist on the Axes which can be used to\ngenerate entries for the resulting legend - it is worth noting however that\nnot all artists can be added to a legend, at which point a \"proxy\" will have\nto be created (see `proxy_legend_handles` for further details).\n\nFor full control of what is being added to the legend, it is common to pass\nthe appropriate handles directly to :func:`legend`::\n\n    line_up, = plt.plot([1,2,3], label='Line 2')\n    line_down, = plt.plot([3,2,1], label='Line 1')\n    plt.legend(handles=[line_up, line_down])\n\nIn some cases, it is not possible to set the label of the handle, so it is\npossible to pass through the list of labels to :func:`legend`::\n\n    line_up, = plt.plot([1,2,3], label='Line 2')\n    line_down, = plt.plot([3,2,1], label='Line 1')\n    plt.legend([line_up, line_down], ['Line Up', 'Line Down'])\n\n\n\nCreating artists specifically for adding to the legend (aka. Proxy artists)\n===========================================================================\n\nNot all handles can be turned into legend entries automatically,\nso it is often necessary to create an artist which *can*. Legend handles\ndon't have to exists on the Figure or Axes in order to be used.\n\nSuppose we wanted to create a legend which has an entry for some data which\nis represented by a red color:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\n\nred_patch = mpatches.Patch(color='red', label='The red data')\nplt.legend(handles=[red_patch])\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are many supported legend handles, instead of creating a patch of color\nwe could have created a line with a marker:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.lines as mlines\n\nblue_line = mlines.Line2D([], [], color='blue', marker='*',\n                          markersize=15, label='Blue stars')\nplt.legend(handles=[blue_line])\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Legend location\n===============\n\nThe location of the legend can be specified by the keyword argument\n*loc*. Please see the documentation at :func:`legend` for more details.\n\nThe ``bbox_to_anchor`` keyword gives a great degree of control for manual\nlegend placement. For example, if you want your axes legend located at the\nfigure's top right-hand corner instead of the axes' corner, simply specify\nthe corner's location, and the coordinate system of that location::\n\n    plt.legend(bbox_to_anchor=(1, 1),\n               bbox_transform=plt.gcf().transFigure)\n\nMore examples of custom legend placement:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plt.subplot(211)\nplt.plot([1, 2, 3], label=\"test1\")\nplt.plot([3, 2, 1], label=\"test2\")\n\n# Place a legend above this subplot, expanding itself to\n# fully use the given bounding box.\nplt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',\n           ncol=2, mode=\"expand\", borderaxespad=0.)\n\nplt.subplot(223)\nplt.plot([1, 2, 3], label=\"test1\")\nplt.plot([3, 2, 1], label=\"test2\")\n# Place a legend to the right of this smaller subplot.\nplt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Multiple legends on the same Axes\n=================================\n\nSometimes it is more clear to split legend entries across multiple\nlegends. Whilst the instinctive approach to doing this might be to call\nthe :func:`legend` function multiple times, you will find that only one\nlegend ever exists on the Axes. This has been done so that it is possible\nto call :func:`legend` repeatedly to update the legend to the latest\nhandles on the Axes, so to persist old legend instances, we must add them\nmanually to the Axes:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "line1, = plt.plot([1, 2, 3], label=\"Line 1\", linestyle='--')\nline2, = plt.plot([3, 2, 1], label=\"Line 2\", linewidth=4)\n\n# Create a legend for the first line.\nfirst_legend = plt.legend(handles=[line1], loc='upper right')\n\n# Add the legend manually to the current Axes.\nax = plt.gca().add_artist(first_legend)\n\n# Create another legend for the second line.\nplt.legend(handles=[line2], loc='lower right')\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Legend Handlers\n===============\n\nIn order to create legend entries, handles are given as an argument to an\nappropriate :class:`~matplotlib.legend_handler.HandlerBase` subclass.\nThe choice of handler subclass is determined by the following rules:\n\n    1. Update :func:`~matplotlib.legend.Legend.get_legend_handler_map`\n       with the value in the ``handler_map`` keyword.\n    2. Check if the ``handle`` is in the newly created ``handler_map``.\n    3. Check if the type of ``handle`` is in the newly created\n       ``handler_map``.\n    4. Check if any of the types in the ``handle``'s mro is in the newly\n       created ``handler_map``.\n\nFor completeness, this logic is mostly implemented in\n:func:`~matplotlib.legend.Legend.get_legend_handler`.\n\nAll of this flexibility means that we have the necessary hooks to implement\ncustom handlers for our own type of legend key.\n\nThe simplest example of using custom handlers is to instantiate one of the\nexisting :class:`~matplotlib.legend_handler.HandlerBase` subclasses. For the\nsake of simplicity, let's choose :class:`matplotlib.legend_handler.HandlerLine2D`\nwhich accepts a ``numpoints`` argument (note numpoints is a keyword\non the :func:`legend` function for convenience). We can then pass the mapping\nof instance to Handler as a keyword to legend.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from matplotlib.legend_handler import HandlerLine2D\n\nline1, = plt.plot([3, 2, 1], marker='o', label='Line 1')\nline2, = plt.plot([1, 2, 3], marker='o', label='Line 2')\n\nplt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, \"Line 1\" now has 4 marker points, where \"Line 2\" has 2 (the\ndefault). Try the above code, only change the map's key from ``line1`` to\n``type(line1)``. Notice how now both :class:`~matplotlib.lines.Line2D` instances\nget 4 markers.\n\nAlong with handlers for complex plot types such as errorbars, stem plots\nand histograms, the default ``handler_map`` has a special ``tuple`` handler\n(:class:`~matplotlib.legend_handler.HandlerTuple`) which simply plots\nthe handles on top of one another for each item in the given tuple. The\nfollowing example demonstrates combining two legend keys on top of one another:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from numpy.random import randn\n\nz = randn(10)\n\nred_dot, = plt.plot(z, \"ro\", markersize=15)\n# Put a white cross over some of the data.\nwhite_cross, = plt.plot(z[:5], \"w+\", markeredgewidth=3, markersize=15)\n\nplt.legend([red_dot, (red_dot, white_cross)], [\"Attr A\", \"Attr A+B\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The :class:`~matplotlib.legend_handler.HandlerTuple` class can also be used to\nassign several legend keys to the same entry:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from matplotlib.legend_handler import HandlerLine2D, HandlerTuple\n\np1, = plt.plot([1, 2.5, 3], 'r-d')\np2, = plt.plot([3, 2, 1], 'k-o')\n\nl = plt.legend([(p1, p2)], ['Two keys'], numpoints=1,\n               handler_map={tuple: HandlerTuple(ndivide=None)})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Implementing a custom legend handler\n------------------------------------\n\nA custom handler can be implemented to turn any handle into a legend key (handles\ndon't necessarily need to be matplotlib artists).\nThe handler must implement a \"legend_artist\" method which returns a\nsingle artist for the legend to use. Signature details about the \"legend_artist\"\nare documented at :meth:`~matplotlib.legend_handler.HandlerBase.legend_artist`.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.patches as mpatches\n\n\nclass AnyObject(object):\n    pass\n\n\nclass AnyObjectHandler(object):\n    def legend_artist(self, legend, orig_handle, fontsize, handlebox):\n        x0, y0 = handlebox.xdescent, handlebox.ydescent\n        width, height = handlebox.width, handlebox.height\n        patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',\n                                   edgecolor='black', hatch='xx', lw=3,\n                                   transform=handlebox.get_transform())\n        handlebox.add_artist(patch)\n        return patch\n\n\nplt.legend([AnyObject()], ['My first handler'],\n           handler_map={AnyObject: AnyObjectHandler()})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively, had we wanted to globally accept ``AnyObject`` instances without\nneeding to manually set the ``handler_map`` keyword all the time, we could have\nregistered the new handler with::\n\n    from matplotlib.legend import Legend\n    Legend.update_default_handler_map({AnyObject: AnyObjectHandler()})\n\nWhilst the power here is clear, remember that there are already many handlers\nimplemented and what you want to achieve may already be easily possible with\nexisting classes. For example, to produce elliptical legend keys, rather than\nrectangular ones:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from matplotlib.legend_handler import HandlerPatch\n\n\nclass HandlerEllipse(HandlerPatch):\n    def create_artists(self, legend, orig_handle,\n                       xdescent, ydescent, width, height, fontsize, trans):\n        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent\n        p = mpatches.Ellipse(xy=center, width=width + xdescent,\n                             height=height + ydescent)\n        self.update_prop(p, orig_handle, legend)\n        p.set_transform(trans)\n        return [p]\n\n\nc = mpatches.Circle((0.5, 0.5), 0.25, facecolor=\"green\",\n                    edgecolor=\"red\", linewidth=3)\nplt.gca().add_patch(c)\n\nplt.legend([c], [\"An ellipse, not a rectangle\"],\n           handler_map={mpatches.Circle: HandlerEllipse()})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
